home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / collections.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  7KB  |  134 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = [
  5.     'deque',
  6.     'defaultdict',
  7.     'namedtuple']
  8. from _abcoll import *
  9. import _abcoll
  10. __all__ += _abcoll.__all__
  11. from _collections import deque, defaultdict
  12. from operator import itemgetter as _itemgetter
  13. from keyword import iskeyword as _iskeyword
  14. import sys as _sys
  15.  
  16. def namedtuple(typename, field_names, verbose = False):
  17.     """Returns a new subclass of tuple with named fields.
  18.  
  19.     >>> Point = namedtuple('Point', 'x y')
  20.     >>> Point.__doc__                   # docstring for the new class
  21.     'Point(x, y)'
  22.     >>> p = Point(11, y=22)             # instantiate with positional args or keywords
  23.     >>> p[0] + p[1]                     # indexable like a plain tuple
  24.     33
  25.     >>> x, y = p                        # unpack like a regular tuple
  26.     >>> x, y
  27.     (11, 22)
  28.     >>> p.x + p.y                       # fields also accessable by name
  29.     33
  30.     >>> d = p._asdict()                 # convert to a dictionary
  31.     >>> d['x']
  32.     11
  33.     >>> Point(**d)                      # convert from a dictionary
  34.     Point(x=11, y=22)
  35.     >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
  36.     Point(x=100, y=22)
  37.  
  38.     """
  39.     if isinstance(field_names, basestring):
  40.         field_names = field_names.replace(',', ' ').split()
  41.     
  42.     field_names = tuple(map(str, field_names))
  43.     for name in (typename,) + field_names:
  44.         if not all((lambda .0: for c in .0:
  45. if not c.isalnum():
  46. passc == '_')(name)):
  47.             raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
  48.         all((lambda .0: for c in .0:
  49. if not c.isalnum():
  50. passc == '_')(name))
  51.         if _iskeyword(name):
  52.             raise ValueError('Type names and field names cannot be a keyword: %r' % name)
  53.         _iskeyword(name)
  54.         if name[0].isdigit():
  55.             raise ValueError('Type names and field names cannot start with a number: %r' % name)
  56.         name[0].isdigit()
  57.     
  58.     seen_names = set()
  59.     for name in field_names:
  60.         if name.startswith('_'):
  61.             raise ValueError('Field names cannot start with an underscore: %r' % name)
  62.         name.startswith('_')
  63.         if name in seen_names:
  64.             raise ValueError('Encountered duplicate field name: %r' % name)
  65.         name in seen_names
  66.         seen_names.add(name)
  67.     
  68.     numfields = len(field_names)
  69.     argtxt = repr(field_names).replace("'", '')[1:-1]
  70.     reprtxt = ', '.join((lambda .0: for name in .0:
  71. '%s=%%r' % name)(field_names))
  72.     dicttxt = ', '.join((lambda .0: for pos, name in .0:
  73. '%r: t[%d]' % (name, pos))(enumerate(field_names)))
  74.     template = "class %(typename)s(tuple):\n        '%(typename)s(%(argtxt)s)' \n\n        __slots__ = () \n\n        _fields = %(field_names)r \n\n        def __new__(_cls, %(argtxt)s):\n            return _tuple.__new__(_cls, (%(argtxt)s)) \n\n        @classmethod\n        def _make(cls, iterable, new=tuple.__new__, len=len):\n            'Make a new %(typename)s object from a sequence or iterable'\n            result = new(cls, iterable)\n            if len(result) != %(numfields)d:\n                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))\n            return result \n\n        def __repr__(self):\n            return '%(typename)s(%(reprtxt)s)' %% self \n\n        def _asdict(t):\n            'Return a new dict which maps field names to their values'\n            return {%(dicttxt)s} \n\n        def _replace(_self, **kwds):\n            'Return a new %(typename)s object replacing specified fields with new values'\n            result = _self._make(map(kwds.pop, %(field_names)r, _self))\n            if kwds:\n                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())\n            return result \n\n        def __getnewargs__(self):\n            return tuple(self) \n\n" % locals()
  75.     for i, name in enumerate(field_names):
  76.         template += '        %s = _property(_itemgetter(%d))\n' % (name, i)
  77.     
  78.     if verbose:
  79.         print template
  80.     
  81.     namespace = dict(_itemgetter = _itemgetter, __name__ = 'namedtuple_%s' % typename, _property = property, _tuple = tuple)
  82.     
  83.     try:
  84.         exec template in namespace
  85.     except SyntaxError:
  86.         e = None
  87.         raise SyntaxError(e.message + ':\n' + template)
  88.  
  89.     result = namespace[typename]
  90.     if hasattr(_sys, '_getframe'):
  91.         result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
  92.     
  93.     return result
  94.  
  95. if __name__ == '__main__':
  96.     from cPickle import loads, dumps
  97.     Point = namedtuple('Point', 'x, y', True)
  98.     p = Point(x = 10, y = 20)
  99.     if not p == loads(dumps(p)):
  100.         raise AssertionError
  101.     
  102.     class Point(namedtuple('Point', 'x y')):
  103.         __slots__ = ()
  104.         
  105.         def hypot(self):
  106.             return (self.x ** 2 + self.y ** 2) ** 0.5
  107.  
  108.         hypot = property(hypot)
  109.         
  110.         def __str__(self):
  111.             return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
  112.  
  113.  
  114.     for p in (Point(3, 4), Point(14, 5 / 7)):
  115.         print p
  116.     
  117.     
  118.     class Point(namedtuple('Point', 'x y')):
  119.         '''Point class with optimized _make() and _replace() without error-checking'''
  120.         __slots__ = ()
  121.         _make = classmethod(tuple.__new__)
  122.         
  123.         def _replace(self, _map = map, **kwds):
  124.             return self._make(_map(kwds.get, ('x', 'y'), self))
  125.  
  126.  
  127.     print Point(11, 22)._replace(x = 100)
  128.     Point3D = namedtuple('Point3D', Point._fields + ('z',))
  129.     print Point3D.__doc__
  130.     import doctest
  131.     TestResults = namedtuple('TestResults', 'failed attempted')
  132.     print TestResults(*doctest.testmod())
  133.  
  134.